import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

// 创建store
const foodStore = createSlice({
    name: 'foods',
    initialState: {
        foodsList: [],
        activeIndex: 0,
        cartList: []
    },
    reducers: {
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        addCart(state, action) {
            // 是否添加过商品
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        // 增加商品数量
        incerCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        // 减商品数量
        decerCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item.count === 0) return
            item.count--
        },
        // 清除购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})

const { setFoodsList, changeActiveIndex, addCart, incerCount, decerCount, clearCart } = foodStore.actions

// 创建异步请求获取数据
const fetchFoodsList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3004/takeaway')
        dispatch(setFoodsList(res.data))
    }
}

export { fetchFoodsList, changeActiveIndex, addCart, incerCount, decerCount, clearCart }

const reducer = foodStore.reducer

export default reducer